package org.yunai.yfserver.server;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 实现一个可以命名的ThreadFactory，以易于定位线程池<br />
 * 参照{@link java.util.concurrent.Executors#defaultThreadFactory()}
 * User: yunai
 * Date: 13-3-28
 * Time: 下午2:33
 */
public class NamedThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public NamedThreadFactory(Class<?> clazz) {
        this(clazz, null);
    }

    /**
     * @param clazz 类
     * @param prefix 用于防止相同的类产生相同的namePrefix
     */
    public NamedThreadFactory(Class<?> clazz, String prefix) {
        SecurityManager s = System.getSecurityManager();
        this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (clazz == null) {
            namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
        } else {
            String tempNamePrefix = clazz.getSimpleName();
            if (prefix != null && prefix.length() > 0) {
                tempNamePrefix += ("-" + prefix);
            }
            tempNamePrefix += "-thread-";
            namePrefix = tempNamePrefix;
        }
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
